package com.example.springboot.global;

import com.example.springboot.exception.BusException;
import com.example.springboot.pojo.vo.GlobalResultVo;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author: wyb
 * @date: 2021/10/29 10:54
 * @describe: 全局异常
 * @vision 1.0
 */
//根据Controller层用的是@Controller还是@RestController来决定
//@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionAdvice {
    
    /**
     * @Author wyb
     * @Description 捕获参数校验异常
     * @Date 10:57 2021/10/29
     * @Param [e]
     * @return java.lang.String
     **/
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public GlobalResultVo MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        return GlobalResultVo.error(objectError.getDefaultMessage());
    }


    /**
     * @Author wyb
     * @Description 捕获业务异常
     * @Date 11:07 2021/10/29
     * @Param [e]
     * @return java.lang.String
     **/
    @ExceptionHandler(BusException.class)
    public GlobalResultVo APIExceptionHandler(BusException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        return GlobalResultVo.error(e.getCode(),e.getMsg(),sw.toString());
    }


    /**
     * @Author wyb
     * @Description 捕获其他异常
     * @Date 11:07 2021/10/29
     * @Param [e]
     * @return java.lang.String
     **/
    @ExceptionHandler(Exception.class)
    public GlobalResultVo APIExceptionHandler(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        return GlobalResultVo.error(e.getMessage(),sw.toString());
    }

}
